package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.tbit.uqbike.object.pojo.RideFeeLog;
import com.tbit.uqbike.object.pojo.dto.RideFeeLogDownloadDTO;
import com.tbit.uqbike.object.pojo.dto.RideFeeLogStatisticsDTO;
import com.tbit.uqbike.object.pojo.dto.SubAccountLogDownloadDTO;
import com.tbit.uqbike.object.pojo.vo.*;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.base.TokenService;
import com.tbit.uqbike.service.business.SubAccountLogService;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.csv.annotations.AsyncDownload;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 分账日志
 *
 * @Author:BUGTian
 * @DATE: 2022/5/26
 */
@RestController
@RequestMapping("/subAccountLog")
public class SubAccountLogController {

    @Autowired
    private SubAccountLogService subAccountLogService;
    @Resource
    private TokenService tokenService;


    /**
     * 分页查询分账明细
     *
     * @param page        当前页码
     * @param size        每页显示的行
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param userNO      adaPay商户下的用户id
     * @param buyOrderNO  订单编号
     * @return
     */
    @GetMapping("/querySubAccountLogPage")
    public Result<PageResult<SubAccountLogVO>> querySubAccountLogPage(HttpServletRequest request, @NotNull Integer page, @NotNull Integer size, Date startTime, Date endTime, @NotNull Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<SubAccountLogVO> pageResult = subAccountLogService.querySubAccountLogPage(login, page, size, startTime, endTime, accountId, adAccountId, userNO, buyOrderNO,confirmId, type);
        return Result.success(pageResult);
    }

    /**
     * 分账明细导出
     *
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param userNO      adaPay商户下的用户id
     * @param buyOrderNO  订单编号
     * @return
     */
    @GetMapping("/exportSubAccountLog")
    public Result exportSubAccountLog(HttpServletRequest request, Date startTime, Date endTime, @NotNull Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        LoginInfo login = BaseController.getLogin(request);
        List<SubAccountLogVO> logExportVOS = subAccountLogService.exportSubAccountLog(login, startTime, endTime, accountId, adAccountId, userNO, buyOrderNO,confirmId,type);
        ExcelUtil<SubAccountLogVO> excel = new ExcelUtil<>(SubAccountLogVO.class);
        JsonResult jsonResult = excel.exportExcel(logExportVOS, "分账明细");
        return Result.success(jsonResult.getData());
    }

    /**
     * 分账明细账单下载（csv导出）
     * @return
     */
    @AsyncDownload(defaultFileName = "分账明细")
    @GetMapping("/downloadSubAccountLog")
    public Result<String> downloadSubAccountLog(SubAccountLogDownloadDTO downloadDTO) {
        LoginInfo loginInfo = tokenService.getLoginInfo(downloadDTO.getToken());
        return Result.success(subAccountLogService.downloadSubAccountLog(loginInfo, downloadDTO.getStartTime(), downloadDTO.getEndTime(), downloadDTO.getAccountId(), downloadDTO.getAdAccountId(), downloadDTO.getUserNO(), downloadDTO.getBuyOrderNO(),downloadDTO.getConfirmId(), downloadDTO.getType()));
    }


    /**
     * 退款明细账单下载（csv导出）
     * @return
     */
    @AsyncDownload(defaultFileName = "退款明细")
    @GetMapping("/downloadSubAccountUserRefund")
    public Result<String> downloadSubAccountUserRefund(SubAccountLogDownloadDTO downloadDTO) {
        LoginInfo loginInfo = tokenService.getLoginInfo(downloadDTO.getToken());
        return Result.success(subAccountLogService.downloadSubAccountUserRefund(loginInfo, downloadDTO.getStartTime(), downloadDTO.getEndTime(), downloadDTO.getAccountId(), downloadDTO.getAdAccountId(), downloadDTO.getUserNO(), downloadDTO.getBuyOrderNO(),downloadDTO.getConfirmId(), downloadDTO.getType()));
    }




    /**
     * 分页查询分账统计-总览
     *
     * @param page        当前页码
     * @param size        每页显示的行
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param userNO      adaPay商户下的用户id
     * @return
     */
    @GetMapping("/querySubAccountLogOverviewPage")
    public Result<PageResult<SubAccountLogOverviewVO>> querySubAccountLogOverviewPage(HttpServletRequest request, @NotNull Integer page, @NotNull Integer size, @NotNull Integer accountId, Integer adAccountId, Date startTime, Date endTime, String userNO) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<SubAccountLogOverviewVO> pageResult = subAccountLogService.querySubAccountLogOverviewPage(login, page, size, startTime, endTime, accountId, adAccountId, userNO);
        return Result.success(pageResult);
    }

    /**
     * 分账统计-总览导出
     *
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param userNO      adaPay商户下的用户id
     * @return
     */
    @GetMapping("/exportSubAccountLogOverviewPage")
    public Result exportSubAccountLogOverviewPage(HttpServletRequest request, @NotNull Integer accountId, Integer adAccountId, Date startTime, Date endTime, String userNO) {
        LoginInfo login = BaseController.getLogin(request);
        List<SubAccountLogOverViewExportVO> list = subAccountLogService.exportSubAccountLogOverviewPage(login, startTime, endTime, accountId, adAccountId, userNO);
        ExcelUtil<SubAccountLogOverViewExportVO> excel = new ExcelUtil<>(SubAccountLogOverViewExportVO.class);
        JsonResult jsonResult = excel.exportExcel(list, "分账统计-总览");
        return Result.success(jsonResult.getData());
    }

    /**
     * 分页查询分账统计-按天统计
     *
     * @param page        当前页码
     * @param size        每页显示的行
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param userNO      adaPay商户下的用户id
     * @return
     */
    @GetMapping("/querySubAccountLogOverviewPageByDay")
    public Result<PageResult<SubAccountLogOverviewVO>> querySubAccountLogOverviewPageByDay(HttpServletRequest request, @NotNull Integer page, @NotNull Integer size, @NotNull Integer accountId, Integer adAccountId, Date startTime, Date endTime, String userNO) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<SubAccountLogOverviewVO> pageResult = subAccountLogService.querySubAccountLogOverviewPageByDay(login, page, size, startTime, endTime, accountId, adAccountId, userNO);
        return Result.success(pageResult);
    }

    /**
     * 分账统计-按天统计导出
     *
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param userNO      adaPay商户下的用户id
     * @return
     */
    @GetMapping("/exportSubAccountLogOverviewPageByDay")
    public Result exportSubAccountLogOverviewPageByDay(HttpServletRequest request, @NotNull Integer accountId, Integer adAccountId, Date startTime, Date endTime, String userNO) {
        LoginInfo login = BaseController.getLogin(request);
        List<SubAccountLogOverviewVO> list = subAccountLogService.exportSubAccountLogOverviewPageByDay(login, startTime, endTime, accountId, adAccountId, userNO);
        ExcelUtil<SubAccountLogOverviewVO> excel = new ExcelUtil<>(SubAccountLogOverviewVO.class);
        JsonResult jsonResult = excel.exportExcel(list, "分账统计-按天统计");
        return Result.success(jsonResult.getData());
    }


    /**
     * 分页查询退款明细
     *
     * @param page        当前页码
     * @param size        每页显示的行
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param userNO      adaPay商户下的用户id
     * @param buyOrderNO  订单编号
     * @return
     */
    @GetMapping("/querySubAccountUserRefund")
    public Result<PageResult<SubAccountUserRefundVO>> querySubAccountUserRefund(HttpServletRequest request, @NotNull Integer page, @NotNull Integer size, Date startTime, Date endTime, @NotNull Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<SubAccountUserRefundVO> pageResult = subAccountLogService.querySubAccountUserRefund(login, page, size, startTime, endTime, accountId, adAccountId, userNO, buyOrderNO, confirmId,type);
        return Result.success(pageResult);
    }

    /**
     * 退款明细导出
     *
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param userNO      adaPay商户下的用户id
     * @param buyOrderNO  订单编号
     * @return
     */
    @GetMapping("/exportSubAccountUserRefund")
    public Result exportSubAccountUserRefund(HttpServletRequest request, Date startTime, Date endTime, @NotNull Integer accountId, Integer adAccountId, String userNO, String buyOrderNO,String confirmId,String type) {
        LoginInfo login = BaseController.getLogin(request);
        List<SubAccountUserRefundVO> list = subAccountLogService.exportSubAccountUserRefund(login, startTime, endTime, accountId, adAccountId, userNO, buyOrderNO,confirmId,type);
        ExcelUtil<SubAccountUserRefundVO> excel = new ExcelUtil<>(SubAccountUserRefundVO.class);
        JsonResult jsonResult = excel.exportExcel(list, "分账详情-退款明细");
        return Result.success(jsonResult.getData());
    }


    /**
     * 根据支付平台订单号查询退款详情
     * @param brandId 品牌编号
     * @param paymentId 支付平台订单号
     * @return
     */
    @GetMapping("/queryRefundDetail")
    public Result<List<SubAccountRefundLogVO>> queryRefundDetail(Integer brandId, String paymentId) {
        List<SubAccountRefundLogVO> subAccountRefundLogVOS = subAccountLogService.queryRefundDetail(brandId, paymentId);
        return Result.success(subAccountRefundLogVOS);
    }


    /**
     * 分页查询分账账户提现日志
     *
     * @param page             当前页码
     * @param size             每页显示的行
     * @param accountId        品牌id
     * @param startTime        开始时间
     * @param endTime          结束时间
     * @param accountUserPhone 操作人手机号
     * @param subAccountId     分账账户id
     * @param schedule         提现进度
     * @param type             提现平台 0-网页平台 1-汇付平台
     * @return
     */
    @GetMapping("/queryWithdrawalLog")
    public Result<PageResult<SubAccountWithdrawalLogVO>> queryWithdrawalLog(@NotNull Integer accountId, @NotNull Integer page, @NotNull Integer size, Date startTime, Date endTime, String accountUserPhone, Integer subAccountId, Integer schedule, Integer type) {
        PageResult<SubAccountWithdrawalLogVO> result = subAccountLogService.queryWithdrawalLog(page, size, accountId, startTime, endTime, accountUserPhone, subAccountId, schedule, type);
        return Result.success(result);
    }

    /**
     * 导出分账账户提现日志
     *
     * @param accountId        品牌id
     * @param startTime        开始时间
     * @param endTime          结束时间
     * @param accountUserPhone 操作人手机号
     * @param subAccountId     分账账户id
     * @param schedule         分账账户id
     * @return
     */
    @GetMapping("/exportWithdrawalLog")
    public Result exportWithdrawalLog(@NotNull Integer accountId, Date startTime, Date endTime, String accountUserPhone, Integer subAccountId, Integer schedule, Integer type) {
        PageResult<SubAccountWithdrawalLogVO> result = subAccountLogService.queryWithdrawalLog(1, 65535, accountId, startTime, endTime, accountUserPhone, subAccountId, schedule, type);
        List<SubAccountWithdrawalLogVO> list = result.getList();
        //单位转换
        list.forEach(SubAccountWithdrawalLogVO::unitConversion);
        ExcelUtil<SubAccountWithdrawalLogVO> excel = new ExcelUtil<>(SubAccountWithdrawalLogVO.class);
        JsonResult withdrawalLog = excel.exportExcel(list, "分账账户提现历史");
        return Result.success(withdrawalLog.getData());
    }

    /**
     * 分页查询订单收费记录
     *
     * @param page      当前页码
     * @param size      每页显示的行
     * @param brandId   品牌id
     * @param accountId 区域id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param type      订单类型
     * @return
     */
    @GetMapping("/queryRideFeeLogPage")
    public Result<PageResult<RideFeeLog>> queryRideFeeLogPage(@NotNull Integer page, @NotNull Integer size, @NotNull Integer brandId, @NotNull Integer accountId, Date startTime, Date endTime, Integer type) {
        PageResult<RideFeeLog> pageResult = subAccountLogService.queryRideFeeLogPage(page, size, brandId, accountId, startTime, endTime, type);
        return Result.success(pageResult);
    }

    /**
     * 订单收费记录统计
     *
     * @param page       当前页码
     * @param size       每页显示的行
     * @param brandId    品牌id
     * @param accountIds 区域id,逗号隔开,不传就是全部
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param type       订单类型
     * @return
     */
    @GetMapping("/queryRideFeeLogPageStatistics")
    public Result<RideFeeLogVo> queryRideFeeLogPageStatistics(@NotNull Integer page, @NotNull Integer size, @NotNull Integer brandId, @NotNull String accountIds, Date startTime, Date endTime, Integer type) {
        List<Integer> accountIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(accountIds)) {
            String[] accountArr = accountIds.split(",");
            for (String accountId : accountArr) {
                accountIdList.add(Integer.valueOf(accountId));
            }
        }
        PageResult<RideFeeLog> pageResult = subAccountLogService.queryRideFeeLogPageStatistics(page, size, brandId, accountIdList, startTime, endTime, type);
        RideFeeLogStatisticsDTO rideFeeLogStatisticsDTO = subAccountLogService.selectRideFeeLogStatistics(brandId, accountIdList, startTime, endTime, type);
        String lastTime = subAccountLogService.getRideFeeLogLastTime(brandId, accountIdList, type);
        RideFeeLogVo vo = new RideFeeLogVo();
        vo.setLastTime(lastTime);
        vo.setTotalIncome(rideFeeLogStatisticsDTO == null ? 0 : rideFeeLogStatisticsDTO.getTotalIncome());
        vo.setTotalExpend(rideFeeLogStatisticsDTO == null ? 0 : rideFeeLogStatisticsDTO.getTotalExpend());
        vo.setAdaPayIncome(rideFeeLogStatisticsDTO == null ? 0 : rideFeeLogStatisticsDTO.getAdaPayIncome());
        vo.setAdaPayExpend(rideFeeLogStatisticsDTO == null ? 0 : rideFeeLogStatisticsDTO.getAdaPayExpend());
        vo.setOtherIncome(rideFeeLogStatisticsDTO == null ? 0 : rideFeeLogStatisticsDTO.getOtherIncome());
        vo.setOtherExpend(rideFeeLogStatisticsDTO == null ? 0 : rideFeeLogStatisticsDTO.getOtherExpend());
        vo.setPageResult(pageResult);
        return Result.success(vo);
    }

    /**
     * 订单收费记录账单下载
     *
     * @param downloadDTO
     * @return
     */
    @AsyncDownload(defaultFileName = "订单收费记录账单")
    @PostMapping("/downloadRideFeeLog")
    public Result downloadRideFeeLog(@RequestBody RideFeeLogDownloadDTO downloadDTO) {
        return Result.success(subAccountLogService.downloadRideFeeLog(downloadDTO));
    }

    /**
     * 订单收费记录导出
     *
     * @param brandId   品牌id
     * @param accountId 区域id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param type      订单类型
     * @return
     */
    @GetMapping("/exportRideFeeLogPage")
    public Result exportRideFeeLogPage(@NotNull Integer brandId, @NotNull Integer accountId, Date startTime, Date endTime, Integer type) {
        int count = subAccountLogService.selectRideFeeLogCount(brandId, accountId, startTime, endTime, type);
        if (count > 60000) {
            return Result.error("导出的数量过多，请修改查询条件再进行导出");
        }
        List<RideFeeLog> list = subAccountLogService.exportRideFeeLogPage(brandId, accountId, startTime, endTime, type);
        ExcelUtil<RideFeeLog> excel = new ExcelUtil<>(RideFeeLog.class);
        JsonResult jsonResult = excel.exportExcel(list, "订单收费记录");
        return Result.success(jsonResult.getData());
    }


    /**
     * 订单收费记录汇总
     *
     * @param brandId   品牌id
     * @param accountId 区域id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param type      订单类型
     * @return
     */
    @GetMapping("/queryRideFeeLogTotal")
    public Result<RideFeeLogTotalVO> queryRideFeeLogTotal(@NotNull Integer brandId, @NotNull Integer accountId, Date startTime, Date endTime, Integer type) {
        RideFeeLogTotalVO rideFeeLogTotalVO = subAccountLogService.queryRideFeeLogTotal(brandId, accountId, startTime, endTime, type);
        return Result.success(rideFeeLogTotalVO);
    }


    /**
     * 分账管理单日
     *
     * @return
     */
    @GetMapping("/queryLedgerManagement")
    public Result<  PageResult<LedgerManagementVO>> queryLedgerManagement(HttpServletRequest request,@NotNull Integer page, @NotNull Integer size,@NotNull Integer brandId, @RequestParam(required = false)  List<Integer> accountId, Date startTime, Date endTime, Integer type,String userNO) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<LedgerManagementVO> pageResult   = subAccountLogService.queryLedgerManagement(login,page,size,brandId, accountId, startTime, endTime, type,userNO);
        return Result.success(pageResult);
    }


    /**
     * 分账管理总览
     *
     * @return
     */
    @GetMapping("/queryLedgerManagementAll")
    public Result<PageResult<LedgerManagementVO>> queryLedgerManagementAll(HttpServletRequest request,@NotNull Integer page, @NotNull Integer size,@NotNull Integer brandId, @RequestParam(required = false)  List<Integer> accountId, Date startTime, Date endTime, Integer type,String userNO) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<LedgerManagementVO> pageResult   = subAccountLogService.queryLedgerManagementAll(login,page,size,brandId, accountId, startTime, endTime, type,userNO);
        return Result.success(pageResult);
    }

    /**
     * 单日分账账单下载（csv导出）
     * @NotNull Integer brandId, @NotNull Integer accountId, Date startTime, Date endTime, Integer type
     * @return
     */
    @AsyncDownload(defaultFileName = "单日分账")
    @GetMapping("/downloadLedgerManagement")
    public Result<String> downloadLedgerManagement(  SubAccountLogDownloadDTO downloadDTO) {
        return Result.success(subAccountLogService.downloadLedgerManagement(downloadDTO.getToken(),downloadDTO.getStartTime(), downloadDTO.getEndTime(), downloadDTO.getAccountId(), downloadDTO.getAdAccountIdS(),downloadDTO.getUserNO(), downloadDTO.getType()==null?null:Integer.parseInt(downloadDTO.getType())));
    }

    /**
     * 总览分账账单下载（csv导出）
     * @return
     */
    @AsyncDownload(defaultFileName = "总览分账")
    @GetMapping("/downloadLedgerManagementAll")
    public Result<String> downloadLedgerManagementAll(SubAccountLogDownloadDTO downloadDTO) {
        return Result.success(subAccountLogService.downloadLedgerManagementAll(downloadDTO.getToken(),downloadDTO.getStartTime(), downloadDTO.getEndTime(), downloadDTO.getAccountId(), downloadDTO.getAdAccountIdS(),downloadDTO.getUserNO(),downloadDTO.getType()==null?null:Integer.parseInt(downloadDTO.getType())));
    }


    /**
     * 分页查询分账退款详情（新表）
     * @param request 当前请求
     * @param page 页码
     * @param size 每页数量
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param brandId 品牌id
     * @param areaId 区域id
     * @param userNO 账户编号
     * @param rechargeNO 业务订单号
     * @param adapayNO 汇付订单号
     * @return 分页详情
     */
    @GetMapping("/queryRefundAdapayRecord")
    public Result<PageResult<RefundAdapayRecordVO>> queryRefundAdapayRecord(HttpServletRequest request, @NotNull Integer page, @NotNull Integer size,@NotNull Date startTime,@NotNull Date endTime, @NotNull Integer brandId, Integer areaId, String userNO, String rechargeNO,String adapayNO) {
        LoginInfo login = BaseController.getLogin(request);
        PageResult<RefundAdapayRecordVO> pageResult = subAccountLogService.queryRefundAdapayRecord(login, page, size, startTime, endTime, brandId, areaId, userNO, rechargeNO, adapayNO);
        return Result.success(pageResult);
    }

    /**
     * 导出分账退款详情（新表）
     * @param request 当前请求
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param brandId 品牌id
     * @param areaId 区域id
     * @param userNO 账户编号
     * @param rechargeNO 业务订单号
     * @param adapayNO 汇付订单号
     * @return 文件名
     */
    @GetMapping("/exportRefundAdapayRecord")
    public Result<String> queryRefundAdapayRecord(HttpServletRequest request,Date startTime, Date endTime, @NotNull Integer brandId, Integer areaId, String userNO, String rechargeNO,String adapayNO) {
        LoginInfo login = BaseController.getLogin(request);
        return Result.success(subAccountLogService.downloadRefundAdapayRecord(login, startTime, endTime, brandId, areaId, userNO, rechargeNO, adapayNO));
    }

}
